<template>
  <div class="smartqa-container">
    <a-layout class="smartqa-layout">
      <!-- 侧边栏 -->
      <a-layout-sider
        width="320"
        class="sidebar"
        breakpoint="lg"
        collapsedWidth="0"
        :trigger="null"
      >
        <!-- 知识库面板 -->
        <div class="panel-block">
          <div class="panel-header">
            <h3 class="panel-title">知识库</h3>
            <a-button
              type="link"
              size="small"
              @click="showKBModal = true"
            >
              <template #icon><folder-add-outlined /></template>
              管理
            </a-button>
          </div>
          
          <div class="panel-toolbar">
            <a-input
              v-model:value="kbKeyword"
              placeholder="搜索知识库"
              allowClear
              @change="fetchKBList"
            >
              <template #prefix><search-outlined /></template>
            </a-input>
          </div>
          
          <a-spin :spinning="kbLoading">
            <a-list
              :dataSource="kbList"
              :locale="{ emptyText: '暂无知识库' }"
              class="panel-list"
            >
              <template #renderItem="{ item }">
                <a-list-item
                  :class="['list-item', { selected: selectedKBId === item.id }]"
                  @click="selectKB(item)"
                >
                  <template #actions>
                    <a-popconfirm
                      title="确定删除此知识库?"
                      @confirm="deleteKB(item.id)"
                    >
                      <a-button type="text" danger size="small">
                        <delete-outlined />
                      </a-button>
                    </a-popconfirm>
                  </template>
                  <a-list-item-meta>
                    <template #title>
                      <file-text-outlined />
                      {{ item.title }}
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </div>
        
        <!-- 对话面板 -->
        <div class="panel-block">
          <div class="panel-header">
            <h3 class="panel-title">历史对话</h3>
            <a-button
              type="primary"
              size="small"
              @click="showCreateDialogueModal = true"
            >
              <template #icon><plus-outlined /></template>
              新建
            </a-button>
          </div>
          
          <div class="panel-toolbar">
            <a-input
              v-model:value="dialogueKeyword"
              placeholder="搜索对话"
              allowClear
              @change="fetchDialogueList"
            >
              <template #prefix><search-outlined /></template>
            </a-input>
          </div>
          
          <a-spin :spinning="dialogueLoading">
            <a-list
              :dataSource="dialogueList"
              :locale="{ emptyText: '暂无对话记录' }"
              class="panel-list"
            >
              <template #renderItem="{ item }">
                <a-list-item
                  :class="['list-item', { selected: selectedDialogueId === item.id }]"
                  @click="selectDialogue(item)"
                >
                  <template #actions>
                    <a-popconfirm
                      title="确定删除此对话?"
                      @confirm="deleteDialogue(item.id)"
                    >
                      <a-button type="text" danger size="small">
                        <delete-outlined />
                      </a-button>
                    </a-popconfirm>
                  </template>
                  <a-list-item-meta>
                    <template #title>
                      <message-outlined />
                      {{ item.title }}
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </div>
      </a-layout-sider>
      
      <!-- 主内容区 -->
      <a-layout class="main-content">
        <!-- 聊天区域 -->
        <a-layout-header class="chat-header">
          <div class="header-content">
            <h2 class="chat-title">
              <robot-outlined />
              AI+就医助手
              <a-tag color="green">在线</a-tag>
            </h2>
            <div class="header-actions">
              <a-button
                type="link"
                @click="showHistoryModal = true"
                :disabled="!selectedDialogueId"
              >
                <template #icon><history-outlined /></template>
                历史记录
              </a-button>
            </div>
          </div>
        </a-layout-header>
        
        <a-layout-content class="chat-content">
          <div class="chat-container" ref="chatContainer">
            <!-- 空状态 -->
            <div v-if="messages.length <= 1" class="empty-state">
              <div class="empty-icon">
                <comment-outlined />
              </div>
              <h3>欢迎使用AI+就医助手</h3>
              <p>请先选择知识库和对话，然后开始提问</p>
              <div v-if="!selectedKBId || !selectedDialogueId" class="empty-tips">
                <a-alert
                  v-if="!selectedKBId"
                  message="请先选择知识库"
                  type="info"
                  show-icon
                />
                <a-alert
                  v-if="!selectedDialogueId"
                  message="请先选择或创建对话"
                  type="info"
                  show-icon
                  class="mt-10"
                />
              </div>
            </div>
            
            <!-- 消息列表 -->
            <div v-else class="message-list">
              <div
                v-for="(msg, index) in messages"
                :key="index"
                :class="['message-item', msg.role]"
              >
                <div class="message-avatar">
                  <a-avatar v-if="msg.role === 'user'">
                    <template #icon><user-outlined /></template>
                  </a-avatar>
                  <a-avatar v-else style="background-color: #87d068">
                    <template #icon><robot-outlined /></template>
                  </a-avatar>
                </div>
                <div class="message-content">
                  <div class="message-bubble">
                    {{ msg.content }}
                  </div>
                </div>
              </div>
              
              <div v-if="sending" class="message-item assistant">
                <div class="message-avatar">
                  <a-avatar style="background-color: #87d068">
                    <template #icon><robot-outlined /></template>
                  </a-avatar>
                </div>
                <div class="message-content">
                  <div class="message-bubble">
                    <a-spin size="small" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-layout-content>
        
        <a-layout-footer class="chat-footer">
          <a-input-search
            v-model:value="input"
            placeholder="请输入您的问题..."
            enter-button="发送"
            size="large"
            :loading="sending"
            :disabled="sending || !selectedKBId || !selectedDialogueId"
            @search="sendMessage"
          >
            <template #prefix>
              <edit-outlined />
            </template>
          </a-input-search>
        </a-layout-footer>
      </a-layout>
    </a-layout>
    
    <!-- 新建对话模态框 -->
    <a-modal
      v-model:visible="showCreateDialogueModal"
      title="新建对话"
      :confirm-loading="dialogueCreating"
      @ok="createDialogue"
      @cancel="showCreateDialogueModal = false"
    >
      <a-input
        v-model:value="newDialogueTitle"
        placeholder="请输入对话标题"
        size="large"
        allowClear
      >
        <template #prefix><form-outlined /></template>
      </a-input>
    </a-modal>
    
    <!-- 知识库管理模态框 -->
    <a-modal
      v-model:visible="showKBModal"
      title="知识库管理"
      width="800px"
      :footer="null"
      @cancel="showKBModal = false"
    >
      <div class="kb-manager">
        <div class="kb-uploader">
          <a-upload
            :customRequest="handleUpload"
            :showUploadList="false"
            :disabled="uploading"
            accept=".txt,.pdf,.doc,.docx,.md"
          >
            <a-button type="primary" :loading="uploading">
              <template #icon><upload-outlined /></template>
              上传知识库文件
            </a-button>
          </a-upload>
          <a-input
            v-model:value="kbTitle"
            placeholder="请输入知识库标题"
            style="margin-top: 16px;"
            allowClear
          >
            <template #prefix><file-text-outlined /></template>
          </a-input>
          <a-button
            type="primary"
            style="margin-top: 16px;"
            :loading="kbCreating"
            :disabled="!kbTitle || !kbUrl"
            @click="createKB"
            block
          >
            <template #icon><plus-outlined /></template>
            创建知识库
          </a-button>
        </div>
        
        <a-divider />
        
        <div class="kb-list">
          <a-input-search
            v-model:value="kbModalKeyword"
            placeholder="搜索知识库"
            @search="fetchKBList"
            allowClear
            style="margin-bottom: 16px;"
          >
            <template #prefix><search-outlined /></template>
          </a-input-search>
          
          <a-spin :spinning="kbModalLoading">
            <a-list
              :dataSource="kbModalList"
              :pagination="kbPagination"
              @change="handleKBPageChange"
              :locale="{ emptyText: '暂无知识库' }"
            >
              <template #renderItem="{ item }">
                <a-list-item>
                  <template #actions>
                    <a-popconfirm
                      title="确定删除此知识库?"
                      @confirm="deleteKB(item.id)"
                    >
                      <a-button type="text" danger size="small">
                        <delete-outlined />
                      </a-button>
                    </a-popconfirm>
                  </template>
                  <a-list-item-meta>
                    <template #title>
                      <file-text-outlined />
                      {{ item.title }}
                    </template>
                    <template #description>
                      <span class="kb-url">{{ item.url }}</span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </a-spin>
        </div>
      </div>
    </a-modal>
    
    <!-- 历史记录模态框 -->
    <a-modal
      v-model:visible="showHistoryModal"
      title="历史提问记录"
      width="800px"
      :footer="null"
    >
      <a-spin :spinning="historyLoading">
        <a-list
          :dataSource="historyList"
          :locale="{ emptyText: '暂无历史记录' }"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #title>
                  {{ item.question }}
                </template>
                <template #description>
                  {{ formatTime(item.createTime) }}
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  RobotOutlined,
  UserOutlined,
  SearchOutlined,
  PlusOutlined,
  DeleteOutlined,
  FileTextOutlined,
  MessageOutlined,
  FolderAddOutlined,
  UploadOutlined,
  FormOutlined,
  CommentOutlined,
  HistoryOutlined,
  EditOutlined
} from '@ant-design/icons-vue'
import * as signalR from '@microsoft/signalr' 

// SignalR连接相关
const hubConnection = ref(null)
const isConnected = ref(false)

// 初始化SignalR连接
async function initSignalRConnection() {
  try {
    // 获取token（根据您的认证方式获取，这里假设从localStorage获取）
    const token = localStorage.getItem('accessToken') || ''
    console.log('[SignalR] Token:', token)

    // 创建连接（使用与API相同的基础URL）
    // 创建连接（使用与API相同的基础URL）
    hubConnection.value = new signalR.HubConnectionBuilder()
      .withUrl('http://192.168.0.22:7044/aimedicalassistant/notification', {
        accessTokenFactory: () => token, // 添加token认证
      })
      .withAutomaticReconnect()
      .build()
    
    // 注册接收AI回答的事件处理函数
    hubConnection.value.on('ReceiveAIMedicalAssistantAnswerMessage', (answer) => {
      console.log('[SignalR] 收到AI回答:', answer)
      // 如果正在等待回答，则添加到消息列表中
      if (sending.value) {
        sending.value = false
        messages.value.push({
          role: 'assistant',
          content: answer.replace("<think>","").replace("</think>","")
        })
        scrollToBottom()
      }
    })
    
    // 连接状态变化处理
    hubConnection.value.onreconnecting((error) => {
      console.log('[SignalR] 正在重新连接...', error)
      isConnected.value = false
    })
    
    hubConnection.value.onreconnected(() => {
      console.log('[SignalR] 已重新连接')
      isConnected.value = true
    })
    
    hubConnection.value.onclose((error) => {
      console.log('[SignalR] 连接已关闭', error)
      isConnected.value = false
    })
    
    // 启动连接
    await hubConnection.value.start()
    console.log('[SignalR] 连接成功')
    isConnected.value = true
  } catch (error) {
    console.error('[SignalR] 连接失败:', error)
    message.error('实时通讯连接失败，将无法接收实时回答')
  }
}

// 知识库相关
const kbList = ref([])
const kbModalList = ref([])
const kbLoading = ref(false)
const kbModalLoading = ref(false)
const kbKeyword = ref('')
const kbModalKeyword = ref('')
const kbTitle = ref('')
const kbUrl = ref('')
const selectedKBId = ref(null)
const uploading = ref(false)
const kbCreating = ref(false)
const showKBModal = ref(false)
const kbPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 对话相关
const dialogueList = ref([])
const dialogueLoading = ref(false)
const dialogueKeyword = ref('')
const selectedDialogueId = ref(null)
const newDialogueTitle = ref('')
const dialogueCreating = ref(false)
const showCreateDialogueModal = ref(false)

// 聊天相关
const messages = ref([{ role: 'assistant', content: '您好，我是AI助手，有什么可以帮您？' }])
const input = ref('')
const sending = ref(false)
const chatContainer = ref(null)

// 历史记录相关
const showHistoryModal = ref(false)
const historyList = ref([])
const historyLoading = ref(false)

// 修改发送消息函数，使用SignalR发送问题
async function sendMessage() {
  if (!input.value.trim() || !selectedKBId.value || !selectedDialogueId.value) {
    return
  }

  const question = input.value.trim()
  messages.value.push({
    role: 'user',
    content: question
  })
  input.value = ''
  sending.value = true
  scrollToBottom()

  const token = localStorage.getItem('accessToken') || ''
      const url = 'http://192.168.0.22:7044/api/module/MedicalAssistant/Create/Question'
      const res = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'accept': 'text/plain',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          question,
          knowledgeBaseId: selectedKBId.value,
          dialogueId: selectedDialogueId.value
        })
      })
      
      if (!res.ok) {
        //const text = await res.text()
        throw new Error('接口响应异常: ' + res.status)
      }
      
      const data = await res.json()
      if (data.success) {
        // messages.value.push({
        //   role: 'assistant',
        //   content: data.message || 'AI已收到您的问题，稍后请在历史记录中查看答案。'
        // })
      } else {
        message.error(data.message || 'AI问答失败')
        messages.value.push({
          role: 'assistant',
          content: data.message || 'AI问答失败'
        })
      }

  try {
    // 检查SignalR连接状态
    if (!isConnected.value) {
      await initSignalRConnection()
    }
    
    // 如果SignalR已连接，则通过SignalR发送问题
    if (isConnected.value && hubConnection.value) {
      console.log('[SignalR] 发送问题:', {
        question,
        knowledgeBaseId: selectedKBId.value,
        dialogueId: selectedDialogueId.value
      })
      
      await hubConnection.value.invoke(
        'SendAIMedicalAssistantQuestionMessage',
        question,
        selectedKBId.value,
        selectedDialogueId.value
      )
      
      // 不立即添加回答，等待SignalR的回调
    } else {
      // const token = localStorage.getItem('accessToken') || ''
      // const url = 'http://192.168.0.22:7044/api/module/MedicalAssistant/Create/Question'
      // const res = await fetch(url, {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json',
      //     'accept': 'text/plain',
      //     'Authorization': `Bearer ${token}`
      //   },
      //   body: JSON.stringify({
      //     question,
      //     knowledgeBaseId: selectedKBId.value,
      //     dialogueId: selectedDialogueId.value
      //   })
      // })
      
      // if (!res.ok) {
      //   //const text = await res.text()
      //   throw new Error('接口响应异常: ' + res.status)
      // }
      
      // const data = await res.json()
      // if (data.success) {
      //   messages.value.push({
      //     role: 'assistant',
      //     content: data.message || 'AI已收到您的问题，稍后请在历史记录中查看答案。'
      //   })
      // } else {
      //   message.error(data.message || 'AI问答失败')
      //   messages.value.push({
      //     role: 'assistant',
      //     content: data.message || 'AI问答失败'
      //   })
      // }
    }
  } catch (error) {
    console.error('[AI提问] 请求异常:', error)
    message.error('AI问答失败: ' + (error.message || '未知错误'))
    messages.value.push({
      role: 'assistant',
      content: 'AI问答失败: ' + (error.message || '未知错误')
    })
  } finally {
    if (!isConnected.value) {
      // 如果是HTTP请求，则在finally中结束loading状态
      // SignalR模式下，会在收到回调时结束loading状态
      sending.value = false
    }
    scrollToBottom()
  }
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

// 获取知识库列表
async function fetchKBList() {
  kbLoading.value = true
  kbModalLoading.value = showKBModal.value
  try {
    const params = new URLSearchParams({
      PageNumber: kbPagination.current,
      PageSize: 30, 
      OrderBy: 'Id',
      SortDirection: 'Descending',
      Keyword: kbKeyword.value
    })
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/KnowledgeBase/Page?${params.toString()}`, {
      method: 'GET',
      headers: {
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await res.json()
    if (data.success) {
      kbList.value = data.data
      if (showKBModal.value) {
        kbModalList.value = data.data
        kbPagination.total = data.total
      }
    } else {
      message.error(data.message || '获取知识库失败')
    }
  } catch (error) {
    message.error('获取知识库失败: ' + (error.message || '未知错误'))
  } finally {
    kbLoading.value = false
    kbModalLoading.value = false
  }
}

// 获取对话列表
async function fetchDialogueList() {
  dialogueLoading.value = true
  try {
    const params = new URLSearchParams({
      PageNumber: 1,
      PageSize: 10,
      OrderBy: 'Id',
      SortDirection: 'Descending',
      Keyword: dialogueKeyword.value
    })
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/Dialogue/Page?${params.toString()}`, {
      method: 'GET',
      headers: {
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await res.json()
    if (data.success) {
      dialogueList.value = data.data
      if (data.data.length > 0 && !selectedDialogueId.value) {
        selectedDialogueId.value = data.data[0].id
      }
    } else {
      message.error(data.message || '获取对话列表失败')
    }
  } catch (error) {
    message.error('获取对话列表失败: ' + (error.message || '未知错误'))
  } finally {
    dialogueLoading.value = false
  }
}

// 创建知识库
async function createKB() {
  console.log(kbTitle.value)
  console.log(kbUrl.value)
  if (!kbTitle.value || !kbUrl.value) {
    message.warning('请先上传文件并输入标题')
    return
  }
  kbCreating.value = true
  try {
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch('http://192.168.0.22:7044/api/module/MedicalAssistant/Create/KnowledgeBase', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ url: kbUrl.value, title: kbTitle.value })
    })
    const data = await res.json()
    if (data.success) {
      message.success('知识库创建成功')
      kbTitle.value = ''
      kbUrl.value = ''
      fetchKBList()
    } else {
      message.error(data.message || '知识库创建失败')
    }
  } catch (error) {
    message.error('知识库创建失败: ' + (error.message || '未知错误'))
  } finally {
    kbCreating.value = false
  }
}

// 删除知识库
async function deleteKB(id) {
  try {
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/KnowledgeBase/${id}`, {
      method: 'DELETE',
      headers: {
        'accept': 'application/json',
          'Authorization': `Bearer ${token}`
      }
    })
    const data = await res.json()
    if (data.success) {
      message.success('删除成功')
      fetchKBList()
      if (selectedKBId.value === id) {
        selectedKBId.value = null
      }
    } else {
      message.error(data.message || '删除失败')
    }
  } catch (error) {
    message.error('删除知识库失败: ' + (error.message || '未知错误'))
  }
}

// 创建对话
async function createDialogue() {
  if (!newDialogueTitle.value) {
    message.warning('请输入对话标题')
    return
  }
  dialogueCreating.value = true
  try {
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/Create/Dialogue?title=${encodeURIComponent(newDialogueTitle.value)}`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await res.json()
    if (data.success) {
      message.success('对话创建成功')
      newDialogueTitle.value = ''
      showCreateDialogueModal.value = false
      await fetchDialogueList()
      if (data.id) {
        selectedDialogueId.value = data.id
      }
    } else {
      message.error(data.message || '对话创建失败')
    }
  } catch (error) {
    message.error('创建对话失败: ' + (error.message || '未知错误'))
  } finally {
    dialogueCreating.value = false
  }
}

// 删除对话
async function deleteDialogue(id) {
  try {
    const token = localStorage.getItem('accessToken') || ''
    const res = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/Dialogue/${id}`, {
      method: 'DELETE',
      headers: {
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await res.json()
    if (data.success) {
      message.success('删除成功')
      fetchDialogueList()
      if (selectedDialogueId.value === id) {
        selectedDialogueId.value = null
      }
    } else {
      message.error(data.message || '删除失败')
    }
  } catch (error) {
    message.error('删除对话失败: ' + (error.message || '未知错误'))
  }
}

// 文件上传处理
async function handleUpload({ file }) {
  uploading.value = true
  const formData = new FormData()
  formData.append('file', file)
  try {
    const response = await fetch('http://192.168.0.22:7044/api/module/Upload/file/ai', {
      method: 'POST',
      body: formData
    })
    const data = await response.json()
    if (data.success) {
      kbUrl.value = data.data.src
      if (!kbTitle.value) {
        kbTitle.value = file.name.split('.')[0]
      }
      message.success('文件上传成功')
    } else {
      message.error(data.message || '文件上传失败')
    }
  } catch (error) {
    message.error('文件上传失败: ' + (error.message || '未知错误'))
  } finally {
    uploading.value = false
  }
}

// 获取历史记录
async function fetchHistory() {
  if (!selectedDialogueId.value||!selectedKBId.value) return
  historyLoading.value = true
  try {
    const params = new URLSearchParams({
      PageNumber: 1,
      PageSize: 30, 
      OrderBy: 'Id',
      SortDirection: 'Descending',
      Keyword: '',
      DialogueId: selectedDialogueId.value,
      KnowledgeBaseId: selectedKBId.value
    })
    const token = localStorage.getItem('accessToken') || ''
    const response = await fetch(`http://192.168.0.22:7044/api/module/MedicalAssistant/Question/History?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    const data = await response.json()
    data.data.forEach(item => {
     messages.value.push({
        role: 'user',
        content: item.question
      })
      messages.value.push({
        role: 'assistant',
        content: item.answer.replace("<think>","").replace("</think>","")
      })
    })
 
    if (data.data) {
      historyList.value = data.data
    } else {
      //message.error(data.message || '获取历史记录失败')
    }
  } catch (error) {
    message.error('获取历史记录失败: ' + (error.message || '未知错误'))
  } finally {
    historyLoading.value = false
  }
}

// 格式化时间
function formatTime(timestamp) {
  return new Date(timestamp).toLocaleString()
}

// 选择知识库
function selectKB(item) {
  selectedKBId.value = item.id
  fetchHistory();
  message.success(`已选择知识库: ${item.title}`)
}

// 选择对话
function selectDialogue(item) {
  selectedDialogueId.value = item.id
  fetchHistory();
  message.success(`已选择对话: ${item.title}`)
}

// 处理知识库分页变化
function handleKBPageChange(pagination) {
  kbPagination.current = pagination.current
  kbPagination.pageSize = pagination.pageSize
  fetchKBList()
}

// 监听历史记录模态框
watch(showHistoryModal, (val) => {
  if (val) {
    fetchHistory()
  }
})

// 组件挂载时初始化
onMounted(() => {
  initSignalRConnection()
  fetchKBList()
  fetchDialogueList()
})
</script>

<style scoped>
.smartqa-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

.smartqa-layout {
  height: 80vh;
}


.sidebar {
  background: #fff;
  border-right: 1px solid #f0f0f0;
  padding: 16px;
  overflow-y: auto;
}

.panel-block {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.panel-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  display: flex;
  align-items: center;
}

.panel-toolbar {
  margin-bottom: 16px;
}

.panel-list {
  max-height: 300px;
  overflow-y: auto;
}

.list-item {
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.list-item:hover {
  background-color: #f5f5f5;
}

.list-item.selected {
  background-color: #e6f7ff;
}


.main-content {
  background: #f5f7fa;
}

.chat-header {
  background: #fff;
  padding: 0 24px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  z-index: 1;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
}

.chat-title {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-content {
  padding: 24px;
  overflow-y: auto;
}

.chat-container {
  max-width: 900px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(0, 0, 0, 0.45);
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-tips {
  margin-top: 24px;
  width: 100%;
  max-width: 400px;
}

.mt-10 {
  margin-top: 10px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 12px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
}

.message-item.user .message-bubble {
  background: #1890ff;
  color: #fff;
  border-bottom-right-radius: 0;
}

.message-item.assistant .message-bubble {
  background: #fff;
  border-bottom-left-radius: 0;
}

.chat-footer {
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.04);
}

/* 知识库管理样式 */
.kb-manager {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.kb-uploader {
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.kb-list {
  flex: 1;
  overflow-y: auto;
}

.kb-url {
  font-family: monospace;
  font-size: 12px;
  color: #888;
  word-break: break-all;
}

@media (max-width: 768px) {
  .sidebar {
    width: 100% !important;
    max-width: 100%;
  }
  
  .chat-content {
    padding: 16px;
  }
  
  .message-content {
    max-width: 80%;
  }
}
</style>